﻿using System.Text.Json;

namespace CoHubServerCore.Protocol;

public partial class Packet
{
    // 用户接口                                                   
    public Guid Guid { get; }
    public Guid Source { get; }
    public Guid Destination { get; }
    public DateTime Data { get; }
    public byte Flag { get; }
    public byte Status { get; }
    public Type Type { get; }
    public byte Result { get; }
    public object Content { get; }

    public Packet(Guid guid, Guid source, Guid destination, DateTime data, byte flag, byte status, byte result,
        object content)
    {
        Guid = guid;
        Source = source;
        Destination = destination;
        Data = data;
        Flag = flag;
        Status = status;
        Type = content.GetType();
        Result = result;
        Content = content;
    }

    private Packet(JsonInterface json)
    {
        Guid = Guid.Parse(json.Guid);
        Source = Guid.Parse(json.Source);
        Destination = Guid.Parse(json.Destination);
        Data = DateTime.Parse(json.Date);
        Flag = json.Flag;
        Status = json.Status;
        Type = Type.GetType(json.Type)!;
        Result = json.Result;
        Content = json.Content.Deserialize(Type)!;
    }

    public static Packet FromJson(string str)
    {
        var jsonObj = JsonSerializer.Deserialize<JsonInterface>(str)!;
        return new Packet(jsonObj);
    }

    public string ToJson()
    {
        return JsonSerializer.Serialize(new JsonInterface(this));
    }
}